package com.sl.au.service.impl;

import com.sl.au.entity.CusAndConArea;
import com.sl.au.entity.Customer;
import com.sl.au.entity.KeyContact;
import com.sl.au.repository.CustomerRepository;
import com.sl.au.repository.KeyContactRepository;
import com.sl.au.service.CustomerService;
import com.sl.au.service.QueryService;
import com.sl.utils.DataConverter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

//import org.apache.poi.util.StringUtil;

@Service("CustomerService")
@Transactional
public class CustomerServiceImpl extends BaseServiceImpl implements CustomerService {

	@Autowired
	CustomerRepository cusomertRepository;

	@Autowired
	KeyContactRepository keyContactRepository;

	@Autowired
	QueryService queryService;

	@Override
	public CustomerRepository getRepository() {
		return this.cusomertRepository;
	}

	@Override
	public KeyContactRepository getKeyContactRepository() {
		// TODO Auto-generated method stub
		return this.keyContactRepository;
	}

	@Override
	public List<Customer> getCustomer(int start, int length, String key, String dataFilter, String superior,
			String areaName,String userId) {
		Page<Customer> pages = null;
		Pageable pageable=null;
		if(key==null){
			key="";
		}else{
			key = key.replaceAll("\\s+", "");
		}
		if(dataFilter.equals("所有")){
			pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
			pages = cusomertRepository.findCustomer(key, pageable);
		}else if(dataFilter.equals("本部门")){
			pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
			pages = cusomertRepository.findCustomer(key, superior, pageable);
		}else if(dataFilter.equals("本片区")){
			pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
			pages = cusomertRepository.findCustomer(key, superior, areaName, pageable);
		}else if(dataFilter.equals("本人")){
			pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
			pages = cusomertRepository.findCustomerByPersonId(key, userId, pageable);
		}
		return pages.getContent();
	}

	@Override
	public List<KeyContact> getKeyContacts(int start, int length, String key, String customerId) {
		Page<KeyContact> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		if (StringUtils.hasText(key)) {
			pages = keyContactRepository.findKeyContact(customerId, key, pageable);
		} else {
			pages = keyContactRepository.findKeyContact(customerId, pageable);
		}
		return pages.getContent();
	}

	@Override
	public long codeValidate(String customerId, String customerCode) {
		long count=0;
		if(customerId==null||customerId.equals("")){
			count=cusomertRepository.getCodeCount(customerCode);
		}else{
			Customer customer=cusomertRepository.findByCustomerCode(customerCode);
			if(customer!=null){
				if(!customer.getId().equals(customerId)){
					count=1;
				}
			}
		}
		return count;
	}

	@Override
	public String getCustomerCode() {
		Date date=new Date();
		String code=DataConverter.toDateYMD(date);
		String customerCode="CM"+code+"-";
		while(true){
			int a=(int) (Math.random()*900+100);
			customerCode=customerCode+a;
			long count=cusomertRepository.getCodeCount(customerCode);
			if(count==0) break;
		}
		return customerCode;
	}

	@Override
	public String updataSareaName() {
		@SuppressWarnings("unchecked")
		StringBuilder hql = new StringBuilder();
		hql.append("select aa from CusAndConArea aa where aa.id in (select num.id from CusAndConAreaNum num where num.number=1) and aa.conAreaName<>'' and aa.cusAreaName<>aa.conAreaName");
		Query query=queryService.createQueryHql(hql.toString());
		query.setFirstResult(0).setMaxResults(2);
		Map<String,Object>namedParamsMap=new HashMap<String,Object>();
		List<CusAndConArea> cusAndConAreas = queryService.executeHql(query, namedParamsMap);
		//List<Customer> customers = cusomertRepository.findCustomer();
		if(cusAndConAreas.size()>0){
			for(CusAndConArea cusAndConArea : cusAndConAreas){
				Customer customer = cusomertRepository.findById(cusAndConArea.getId());
				if(customer != null){
					customer.setSaleArea(cusAndConArea.getConSarea());
					cusomertRepository.save(customer);
				}else{
					continue;
				}
			}
		}
		return "'"+cusAndConAreas.size()+"'";
	}

}
